<script setup lang="ts">
import { onMounted, ref } from 'vue'
const currentIndex = ref(0)
const tabbars = ref<HTMLElement[] | null>([])
const line = ref<HTMLElement | null>(null)

const tabbarItem = (el: HTMLElement) => {
  if (tabbars.value) {
    tabbars.value.push(el)
  }
}

const props = defineProps({
  tabs: {
    type: Array,
    default: () => [],
  },
})

const emits = defineEmits(['tabChange'])
const handleChange = (index: number) => {
  currentIndex.value = index
  if (tabbars.value && line.value) {
    const target = tabbars.value[currentIndex.value]
    line.value!.style.left = `${-line.value.offsetWidth / 2}px`
    line.value!.style.transform = `translateX(${
      target.offsetLeft > 0
        ? target.offsetLeft + target.offsetWidth / 2
        : target.offsetWidth / 2
    }px)`
  }
  emits('tabChange', index)
}

const initLine = () => {
  if (tabbars.value && line.value) {
    const target = tabbars.value[currentIndex.value]
    line.value!.style.transition = 'all .3s'
    line.value!.style.left = `${-line.value.offsetWidth / 2}px`
    line.value!.style.transform = `translateX(${
      target.offsetLeft > 0 ? target.offsetLeft : target.offsetWidth / 2
    }px)`
  }
}

onMounted(() => {
  initLine()
})
</script>
<template>
  <div class="tabbar-container">
    <div class="tabbar">
      <div
        class="tabbar-item"
        :ref="tabbarItem"
        v-for="(item, index) in tabs"
        :key="index"
        :class="{ active: currentIndex === index }"
        @click="handleChange(index)"
      >
        {{ item.title }}
      </div>
      <div ref="line" class="line"></div>
    </div>
    <div class="tabbar-content">
      <slot :name="item.name" v-for="(item, index) in tabs" :key="index"></slot>
    </div>
  </div>
</template>

<style lang="less" scoped>
.tabbar-container {
  .tabbar {
    display: flex;
    justify-content: flex-start;
    background-color: #fff;
    padding: 10px 0 0 0;
    position: relative;
    border-bottom: 1px solid #eee;
    .tabbar-item {
      padding: 10px 20px;
      font-size: 14px;
      color: #999;
      cursor: pointer;
      transition: all 0.3s;
      &.active {
        color: #333;
        font-weight: bold;
      }
    }
    .line {
      position: absolute;
      width: 20px;
      height: 2px;
      top: 98%;
      left: 0;
      background-color: rgb(255, 148, 2);
    }
  }
  .tabbar-content {
    padding: 10px;
  }
}

@media screen and (max-width: 528px) {
  .tabbar-container .tabbar-content {
    padding-left: 0;
    padding-right: 0;
  }
}
</style>
